
const { executeInEditMode, ccclass, property } = cc._decorator;

@ccclass
@executeInEditMode
export default class OpacityMaskHelper extends cc.Component {
    @property({
        serializable: true,
        visible: false,
        type: cc.Texture2D,
    })
    _maskTex: cc.Texture2D = null;
    @property(cc.Texture2D)
    get maskTex() {
        return this._maskTex;
    }
    set maskTex(val: cc.Texture2D) {
        this._maskTex = val;
        this.refresh();
    }

    @property({
        serializable: true
    })
    _useRedAlpha = false;

    @property({
        tooltip: "useRedAlpha",
        displayName: "使用黑白图片做透明数据"
    })
    get useRedAlpha() {
        return this._useRedAlpha;
    }
    set useRedAlpha(val: boolean) {
        this._useRedAlpha = val;
        this.refresh();
    }

    @property(cc.Material)
    opacityMaterial: cc.Material = null;

    _sprite: cc.Sprite = null;
    get sprite() {
        if (!this._sprite) {
            let sprite = this.getComponent(cc.Sprite);
            if (!sprite) {
                sprite = this.addComponent(cc.Sprite);
                sprite.setMaterial(0, this.opacityMaterial);
            }
            if (!sprite) {
                cc.error("get OpacityMaskHelper::sprite, error: 不能获得或添加cc.Sprite组件。");
                return;
            }

            let material = sprite.getMaterial(0);
            if (material.name != this.opacityMaterial.name) {
                sprite.setMaterial(0, this.opacityMaterial);
            }
            this._sprite = sprite;
        }
        return this._sprite;
    }

    _material: cc.Material = null;
    get material() {
        return this.sprite.getMaterial(0);
    }

    refresh() {
        if (!this.material) {
            cc.warn("OpacityMaskHelper::refresh, warn: this.material为空");
            return;
        }
        this.material.setProperty("maskTex", this.maskTex);
        this.material.setProperty("useRedAlpha", this.useRedAlpha);
    }
    refreshAfterUpdate() {
        cc.director.once(cc.Director.EVENT_AFTER_UPDATE, this.refresh, this);
    }

    onLoad() {
        this.refresh();
    }
};